import math
import random
import numpy as np
from functools import partial

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor


device = torch.device("cuda:2")

def get_inplanes():
    return [64, 128, 256, 512]


def conv3x3x3(in_planes, out_planes, stride=1):
    return nn.Conv3d(in_planes,
                     out_planes,
                     kernel_size=3,
                     stride=stride,
                     padding=1,
                     bias=False)


def conv1x1x1(in_planes, out_planes, stride=1):
    return nn.Conv3d(in_planes,
                     out_planes,
                     kernel_size=1,
                     stride=stride,
                     bias=False)


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, in_planes, planes, stride=1, downsample=None):
        super().__init__()

        self.conv1 = conv3x3x3(in_planes, planes, stride)
        self.bn1 = nn.BatchNorm3d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3x3(planes, planes)
        self.bn2 = nn.BatchNorm3d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, in_planes, planes, stride=1, downsample=None):
        super().__init__()

        self.conv1 = conv1x1x1(in_planes, planes)
        self.bn1 = nn.BatchNorm3d(planes)
        self.conv2 = conv3x3x3(planes, planes, stride)
        self.bn2 = nn.BatchNorm3d(planes)
        self.conv3 = conv1x1x1(planes, planes * self.expansion)
        self.bn3 = nn.BatchNorm3d(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class ResNet(nn.Module):

    def __init__(self,
                 block,
                 layers,
                 block_inplanes,
                 n_input_channels=2,
                 conv1_t_size=7,
                 conv1_t_stride=1,
                 no_max_pool=False,
                 shortcut_type='B',
                 widen_factor=1.0,
                 n_classes=2):
        super().__init__()

        block_inplanes = [int(x * widen_factor) for x in block_inplanes]

        self.in_planes = block_inplanes[0]
        self.no_max_pool = no_max_pool

        self.conv1 = nn.Conv3d(n_input_channels,
                               self.in_planes,
                               kernel_size=(conv1_t_size, 7, 7),
                               stride=(conv1_t_stride, 2, 2),
                               padding=(conv1_t_size // 2, 3, 3),
                               bias=False)
        self.bn1 = nn.BatchNorm3d(self.in_planes)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool3d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, block_inplanes[0], layers[0],
                                       shortcut_type)
        self.layer2 = self._make_layer(block,
                                       block_inplanes[1],
                                       layers[1],
                                       shortcut_type,
                                       stride=2)
        self.layer3 = self._make_layer(block,
                                       block_inplanes[2],
                                       layers[2],
                                       shortcut_type,
                                       stride=2)
        self.layer4 = self._make_layer(block,
                                       block_inplanes[3],
                                       layers[3],
                                       shortcut_type,
                                       stride=2)

        self.avgpool = nn.AdaptiveAvgPool3d((1, 1, 1))


        self.fc = nn.Linear(block_inplanes[3] * block.expansion, 128)

        self.fc1 = nn.Linear(132, 128)

        self.fc2 = nn.Linear(128, 2)

        self.dropout = nn.Dropout(0.5)



        for m in self.modules():
            if isinstance(m, nn.Conv3d):
                nn.init.kaiming_normal_(m.weight,
                                        mode='fan_out',
                                        nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm3d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _downsample_basic_block(self, x, planes, stride):
        out = F.avg_pool3d(x, kernel_size=1, stride=stride)
        zero_pads = torch.zeros(out.size(0), planes - out.size(1), out.size(2),
                                out.size(3), out.size(4))
        if isinstance(out.data, torch.cuda.FloatTensor):
            zero_pads = zero_pads.cuda()

        out = torch.cat([out.data, zero_pads], dim=1)

        return out

    def _make_layer(self, block, planes, blocks, shortcut_type, stride=1):
        downsample = None
        if stride != 1 or self.in_planes != planes * block.expansion:
            if shortcut_type == 'A':
                downsample = partial(self._downsample_basic_block,
                                     planes=planes * block.expansion,
                                     stride=stride)
            else:
                downsample = nn.Sequential(
                    conv1x1x1(self.in_planes, planes * block.expansion, stride),
                    nn.BatchNorm3d(planes * block.expansion))

        layers = []
        layers.append(
            block(in_planes=self.in_planes,
                  planes=planes,
                  stride=stride,
                  downsample=downsample))
        self.in_planes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.in_planes, planes))

        return nn.Sequential(*layers)

    def _forward_impl(self, x: Tensor, other: Tensor):
        # See note [TorchScript super()]
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = torch.flatten(x, 1)

        x = self.fc(x)

        x2 = torch.cat((x, other), dim=1)

        out = self.dropout(x2)
        out = self.fc1(out)
        out = self.relu(out)
        out = self.dropout(out)
        out = self.fc2(out)


        return x2, out


    def forward(self, x, other, target, use_mixup=False, mixup_alpha=0.5, layer_mix=None, mix_type=None):

        if use_mixup:

            # 确定是mixup还是remix
            mix_function = mix_up(mix_type)

            if layer_mix == None:
                layer_mix = random.randint(0, 4)

            if layer_mix == 0:
                x, y_a, y_b, lam = mix_function(x, target, mixup_alpha)

            x = self.conv1(x)
            x = self.bn1(x)
            x = self.relu(x)
            x = self.maxpool(x)

            x = self.layer1(x)

            if layer_mix == 1:
                x, y_a, y_b, lam = mix_function(x, target, mixup_alpha)

            x = self.layer2(x)

            if layer_mix == 2:
                x, y_a, y_b, lam = mix_function(x, target, mixup_alpha)

            x = self.layer3(x)

            if layer_mix == 3:
                x, y_a, y_b, lam = mix_function(x, target, mixup_alpha)

            x = self.layer4(x)

            if layer_mix == 4:
                x, y_a, y_b, lam = mix_function(x, target, mixup_alpha)

            x = self.avgpool(x)
            x = torch.flatten(x, 1)

            x = self.fc(x)


            x2 = torch.cat((x, other), dim=1)

            out = self.dropout(x2)
            out = self.fc1(out)
            out = self.relu(out)
            out = self.dropout(out)
            out = self.fc2(out)

            return x2, out, y_a, y_b, lam
        else:
            return self._forward_impl(x, other)


def generate_model(model_depth, **kwargs):
    assert model_depth in [10, 18, 34, 50, 101, 152, 200]

    if model_depth == 10:
        model = ResNet(BasicBlock, [1, 1, 1, 1], get_inplanes(), **kwargs)
    elif model_depth == 18:
        model = ResNet(BasicBlock, [2, 2, 2, 2], get_inplanes(), **kwargs)
    elif model_depth == 34:
        model = ResNet(BasicBlock, [3, 4, 6, 3], get_inplanes(), **kwargs)
    elif model_depth == 50:
        model = ResNet(Bottleneck, [3, 4, 6, 3], get_inplanes(), **kwargs)
    elif model_depth == 101:
        model = ResNet(Bottleneck, [3, 4, 23, 3], get_inplanes(), **kwargs)
    elif model_depth == 152:
        model = ResNet(Bottleneck, [3, 8, 36, 3], get_inplanes(), **kwargs)
    elif model_depth == 200:
        model = ResNet(Bottleneck, [3, 24, 36, 3], get_inplanes(), **kwargs)

    return model


# 分配使用manifold-mixup还是remix
def mix_up(name):
    # mixup数据增强方法
    def mixup_data(x, y, alpha):
        '''
        :param x: batch features
        :param y: batch labels
        :param alpha: beta分布参数
        :return: mixup_inputs, pairs of targets, lambda
        '''
        if alpha > 0:
            lam = np.random.beta(alpha, alpha)
        else:
            lam = 1.

        batch_size = x.size()[0]

        index = torch.randperm(batch_size).to(device)

        mixed_x = lam * x + (1 - lam) * x[index, :]
        y_a = y
        y_b = y[index]

        return mixed_x, y_a, y_b, lam

    # remix数据增强方法
    def remix_data(x, y, alpha):
        '''
        :param x: batch features
        :param y: batch labels
        :param alpha: beta分布参数
        :return: mixup_inputs, pairs of targets, lambda
        '''

        num_classes = torch.tensor([487., 144., 24., 68., 20.]).float()
        k = 3.0
        tao = 0.5

        if alpha > 0:
            lam = np.random.beta(alpha, alpha)
        else:
            lam = 1.

        batch_size = x.size()[0]

        index = torch.randperm(batch_size).to(device)

        # 初始化
        x_a = x
        x_b = x[index, :]
        y_a = y
        y_b = y[index]

        x_rm = torch.zeros_like(x)
        y_rm_a = torch.zeros_like(y)
        y_rm_b = torch.zeros_like(y)

        # remix
        for i in range(0, batch_size):

            x_rm[i] = lam * x_a[i] + (1 - lam) * x_b[i]

            # y_return = lamda_y*yi + (1-lamda_y)*yj
            # lamda_y=0, y_return=yj
            if ((num_classes[y_a[i].item()] / num_classes[y_b[i].item()]) >= k) and (lam < tao):
                y_rm_a[i] = y_b[i]
                y_rm_b[i] = y_b[i]

            # lamda_y=1, y_return=yi
            elif ((num_classes[y_a[i].item()] / num_classes[y_b[i].item()]) <= (1.0 / k)) and ((1 - lam) < tao):
                y_rm_a[i] = y_a[i]
                y_rm_b[i] = y_a[i]

            else:
                y_rm_a[i] = y_a[i]
                y_rm_b[i] = y_b[i]

        return x_rm, y_rm_a, y_rm_b, lam


    if name == 'manifold_mixup':
        return mixup_data
    elif name == 'remix':
        return remix_data